<?php

namespace app\api\controller;
use think\Db;

use app\common\controller\Logined;
use app\common\service\BalanceService;
use app\common\service\TradeService;

class Trade extends Logined{
	
	/*
	获取交易列表
	 */
	public function getTradeList(){
		$data =  model('CoinModel')->getCoinList(2);
		if($data){
			$this->retData(0,'success',$data);
		}
	}

	/*
	切换币种
	 */
	public function switchCoin(){
		$cid = P('cid');
		if(empty($cid)){
			$this->retData(1,'缺少参数');
		}
		$data =  model('CoinModel')->getCoinInfo($cid);
		if($data['is_trade'] != 1){
			$this->retData(1,'系统错误');
		}
		if($data){
			$this->retData(0,'success',$data);
		} else {
			$this->retData(0,'fail');
		}
	}

	/*
	挂卖/挂买
	 */
	public function setOrder(){
		$uid     = $this->uid;
		$cid     = P('cid');
		$price   = P('price');
		$amount  = P('amount');
		$paypass = P('paypass');
		$type    = P('type');
		if(empty($uid) || empty($cid) || empty($amount)  || empty($price) || empty($paypass)){
			$this->retData(1,'缺少参数');
		}

		if($amount <= 0 || $price<=0){
			$this->retData(1,'数量或价格有误，请重新输入');
		}

		$coin = model('CoinModel')->getCoinInfo($cid);
		if(empty($coin) || $coin['is_trade'] != 1){
			$this->retData(1,'系统错误');
		}

		$user_paypass = model('UserModel')->getPaypass($uid);
		if($user_paypass != $paypass){
			$this->retData(1,'交易密码错误');
		}
		$pay_info = model('PayInfoModel')->getPayInfo($uid);
		if(empty($pay_info)){
			$this->retData(1,'请至少绑定一种支付方式再挂卖');
		}
		Db::startTrans();
		if($type == 1){
			$min_trade = $coin['min_trade'];
			if($min_trade > 0){
				if($min_trade > $amount){
					$this->retData(1,'最低挂卖数量'.$min_trade);
				}
			}
			$fee_rate      = $coin['trade_fee'];
			$fee           = $amount*$fee_rate;
			$total_amount  = $amount + $fee;
			$check_balance = BalanceService::checkBalance($uid,$cid,$total_amount);
			if(!$check_balance){ 
				$this->retData(1,'余额不足');
			}
			$res = TradeService::setSellOrder($uid,$cid,$amount,$price,$fee_rate,$fee);
		} else {
			$res = TradeService::setBuyOrder($uid,$cid,$amount,$price);
		}
		if($res){
			Db::commit();
			$this->retData(0,'挂单成功');
		} else {
			Db::rollback();
			$this->retData(1,'挂单失败');
		}
	}
	/*
	撤销挂卖
	 */
	public function undoOrder(){
		$id = P('id');
		$uid = $this->uid;
		if(empty($id) || empty($uid)){
			$this->retData(1,'缺少参数');
		}
		Db::startTrans();
		$order_info = model('TradeListModel')->getOrderInfo($id);
		if($order_info['status'] != 1){
			$this->retData(1,'订单状态错误');
		}
		if($order_info['uid'] != $uid){
			$this->retData(1,'系统错误');
		}
		if($order_info['type'] == 1){
			if($order_info['type'] != 1){
				$this->retData(1,'订单类型错误，非卖单');
			}
			$res = TradeService::undoSell($order_info);
		} else{
			if($order_info['type'] != 0){
				$this->retData(1,'订单类型错误，非买单');
			}
			$res = TradeService::undoBuy($id);
		}
		if($res){
			Db::commit();
			$this->retData(0,'撤销成功');
		} else {
			Db::commit();
			$this->retData(1,'撤销失败');
		}
	}


	/*
	获取订单
	 */
	public function getOrder(){
		$uid = $this->uid;
		$cid  = P('cid')?:0;
		$type = P('type');
		$page = P('page')?:1;
		if(empty($uid) || empty($type)){
			return $this->retData(1,'缺少参数');
		}
		//$data = TradeAction::getOrder($uid,$cid,$type);
		$data = model('TradeListModel')->getOrder($uid,$cid,$type,$page);
		foreach ($data as $key => $val) {
			$data[$key]['t_num'] = model('TradeRecordModel')->countComplete($val['uid']);
		}
		if(!empty($data)){
			$this->retData(0,'success',$data);
		} else {
			$this->retData(0,'fail');
		}
	}


	/*
	个人订单
	 */
	public function getSelfOrder(){
		$uid = $this->uid;
		$cid = P('cid')?:'';
		if(empty($uid)){
			$this->retData(1,'缺少参数');
		}
		$data = model('TradeListModel')->getSelfOrder($uid,$cid);
		if(!empty($data)){
			$this->retData(0,'success',$data);
		} else {
			$this->retData(0,'fail');
		}
	}

	/*
	订单详情
	 */
	public function orderDetail(){
		$id = P('id');
		if(empty($id)){
			return $this->retData(1,'缺少参数');
		}
		$data =  model('TradeListModel')->orderDetail($id);
		$data['t_num'] = model('TradeRecordModel')->countComplete($data['uid']);
		if(!empty($data)){
			$this->retData(0,'success',$data);
		} else {
			$this->retData(0,'fail');
		}
	}

	/*
	买入
	 */
	public function buy(){
		$uid = $this->uid;
		$id = P('id');
		$amount = P('amount');
		$paypass = P('paypass');
		if(empty($uid) || empty($id) || empty($amount) || empty($paypass)){
			$this->retData(1,'缺少参数');
		}

		if($amount <= 0){
			$this->retData(1,'购买数量有误，请重新输入');
		}
		Db::startTrans();
		$order_info = model('TradeListModel')->getOrderInfo($id);
		if($order_info['uid'] == $uid || $order_info['status'] != 1 || $order_info['type'] != 1 || $order_info['left_amount']<=0){
			$this->retData(1,'系统错误');
		}

		$pay_info = model('PayInfoModel')->getPayInfo($uid);
		if(empty($pay_info)){
			$this->retData(1,'请至少绑定一种支付方式再买入');
		}

		if($order_info['left_amount'] < $amount){
			$this->retData(1,'最大只能购买'.$order_info['left_amount']);
		}

		$user_paypass = model('UserModel')->getPaypass($uid);
		if($user_paypass != $paypass){
			$this->retData(1,'交易密码错误');
		}
		$cid      = $order_info['cid'];
		$sell_uid = $order_info['uid'];
		$order_id = $order_info['id'];
		$price    = $order_info['price'];
		$data = TradeService::buy($uid,$sell_uid,$order_id,$cid,$amount,$price);
		if($data){
			Db::commit();
			$this->retData(0,'买入成功，请及时打款');
		} else {
			Db::rollback();
			$this->retData(1,'买入失败');
		}
	}


	/*
	卖出
	*/
	public function sell(){
		$uid = $this->uid;
		$id = P('id');
		$amount = P('amount');
		$paypass = P('paypass');
		if(empty($uid) || empty($id) || empty($amount) || empty($paypass)){
			$this->retData(1,'缺少参数');
		}

		if($amount <= 0){
			$this->retData(1,'购买数量有误，请重新输入');
		}
		Db::startTrans();
		$order_info = model('addons/TradeListModel')->getOrderInfo($id);
		if($order_info['uid'] == $uid  || $order_info['status'] != 1 || $order_info['type'] != 0 || $order_info['left_amount']<=0){
			$this->retData(1,'系统错误');
		}

		if($order_info['left_amount'] < $amount){
			$this->retData(1,'最大只能卖出'.$order_info['left_amount']);
		}

		$user_paypass = model('addons/UserModel')->getPaypass($uid);
		if($user_paypass != $paypass){
			$this->retData(1,'交易密码错误');
		}
		$coin = model('CoinModel')->getCoinInfo($order_info['cid']);
		$fee_rate = $coin['trade_fee'];
		$fee = $amount*$fee_rate;
		$total_amount = $amount + $fee;
		$check_balance = BalanceService::checkBalance($uid,$order_info['cid'],$total_amount);
		if(!$check_balance){ 
			$this->retData(1,'余额不足');
		}
		$cid      = $order_info['cid'];
		$buy_uid  = $order_info['uid'];
		$order_id = $order_info['id'];
		$price    = $order_info['price'];
		$res = TradeService::sell($uid,$buy_uid,$order_id,$cid,$amount,$price,$fee);
		if($res){
			Db::commit();
			$this->retData(0,'卖出成功，等待买家打款');
		} else {
			Db::rollback();
			$this->retData(1,'卖出失败');
		}
	}

	/*
	进行中订单
	 */
	public function Tradeing(){
		$uid = $this->uid;
		if(empty($uid)){
			$this->retData(1,'缺少参数');
		}
		$data = TradeService::Tradeing($uid);
		if($data){
			$this->retData(0,'success',$data);
		} else {
			$this->retData(0,'fail');
		}
	}

	/*
	已完成订单
	 */
	public function completeTrade(){
		$uid = $this->uid;
		if(empty($uid)){
			$this->retData(1,'缺少参数');
		}
		$data = TradeService::completeTrade($uid);
		if($data){
			foreach ($data as $key => $val) {
				$data[$key]['t_num'] = model('TradeRecordModel')->countComplete($uid);
			}
		 	$this->retData(0,'success',$data);
		 }  else {
			$this->retData(0,'fail');
		}
	}

	/*
	订单初始化
	 */
	public function initOrder(){
		$cid = P('cid');
		$uid = $this->uid;
		if(empty($uid)){
			$this->retData(1,'缺少参数');
		}
		$veri_coin = model('CoinModel')->getCoinInfo($cid);
		if(empty($veri_coin) || $veri_coin['is_trade'] != 1){
			$this->retData(1,'币种不存在或该币种暂不支持交易');
		}
		$this->retData(0,'success',$veri_coin['price']);
	}

	/*
	订单详情
	 */
	public function getTradeRecord(){
		$id = P('id');
		$uid = $this->uid;
		if(empty($uid) || empty($id)){
			$this->retData(1,'缺少参数');
		}
		//验证
		$trade_info = model('TradeRecordModel')->getTradeInfo($id);
		if($trade_info['sell_uid'] != $uid && $trade_info['buy_uid'] != $uid){
			$this->retData(1,'系统错误');
		} 
		$data = TradeService::getTradeDetail($uid,$id);
		$this->retData(0,'success',$data);
	}

	/*
	标记付款
	 */
	public function confirmPay(){
		$id = P('id');
		$uid = $this->uid;
		$pay_cert = P('pay_cert');
		$remark = P('remark')?:'';
		if(empty($uid) || empty($id) || empty($pay_cert)){
			$this->retData(1,'缺少参数');
		}
		//验证
		$trade_info = model('TradeRecordModel')->getTradeInfo($id);
		if($trade_info['status'] != 1 || $trade_info['buy_uid'] != $uid){
			$this->retData(1,'系统错误');
		} 
		$res = TradeService::confirmPay($id,$pay_cert,$remark);
		if($res){
			$this->retData(0,'标记付款成功');
		} else {
			$this->retData(1,'标记付款失败');
		}
	}

	/*
	确认交易
	 */
	public function confirmTrade(){
		$id = P('id');
		$uid = $this->uid;
		if(empty($uid) || empty($id)){
			$this->retData(1,'缺少参数');
		}
		//验证
		$trade_info = model('TradeRecordModel')->getTradeInfo($id);
		if($trade_info['status'] != 2 || $trade_info['sell_uid'] != $uid){
			return $this->retData(0,'系统错误');
		} 
		$res = TradeService::confirmTrade($id);
		if($res){
			$this->retData(0,'确认收款成功');
		} else {
			$this->retData(1,'确认收款失败');
		}
	}

	/*
	拒绝交易
	 */
	public function refuseTrade(){
		$id = P('id');
		$uid = $this->uid;
		$refuse_remark = P('refuse_remark');
		if(empty($uid) || empty($id) || empty($refuse_remark)){
			$this->retData(1,'缺少参数');
		}
		//验证
		$trade_info = model('TradeRecordModel')->getTradeInfo($id);
		if($trade_info['status'] != 2 || $trade_info['sell_uid'] != $uid){
			$this->retData(1,'系统错误');
		} 
		$res = TradeService::refuseTrade($id,$refuse_remark);
		if($res){
			$this->retData(0,'拒绝收款成功，请等待客服介入');
		} else {
			$this->retData(1,'拒绝收款失败');
		}
	}
}